//
//  IGCalendarView.m
//  TimeTest
//
//  Created by 王鹏宇 on 2018/1/25.
//  Copyright © 2018年 LvJianfeng. All rights reserved.
//

#import "IGCalendarView.h"
#import "NSDate+Formatter.h"
#define LL_SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define LL_SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)
#define Iphone6Scale(x) ((x) * LL_SCREEN_WIDTH / 375.0f)
#import "MonthCollectionCell.h"
@interface IGCalendarView()<UICollectionViewDelegate,UICollectionViewDataSource,MonthCollectionCellDelegate>

@property (nonatomic, strong)UIButton * preBtn;
@property (nonatomic, strong)UIButton * nextBtn;
@property (nonatomic, strong)UILabel * currentMonthLabel;
@property (strong, nonatomic) NSMutableArray *monthsArray;

@property (strong, nonatomic)NSMutableArray <NSMutableArray *>* allMonths;
@property (nonatomic, strong)UICollectionView * collectionView;

@property (strong, nonatomic) NSDate *today;
@property (strong, nonatomic) NSDate *lastDay;
@property (nonatomic)NSUInteger currenIndex;
@end

@implementation IGCalendarView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
      //  [self setupData];
    }
    return self;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
      [self setup];
      //  [self setupData];
    }
    return self;
}
- (UIButton *)preBtn {
    
    if (!_preBtn) {
        
        _preBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_preBtn setImage:[UIImage imageNamed:@"箭头左"] forState:UIControlStateNormal];
        [_preBtn addTarget:self action:@selector(preBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _preBtn;
}

- (UIButton *)nextBtn {
    
    if (!_nextBtn) {
        
        _nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_nextBtn setImage:[UIImage imageNamed:@"箭头右"] forState:UIControlStateNormal];
        [_nextBtn addTarget:self action:@selector(nextBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _nextBtn;
}

- (void)setCloseArray:(NSArray *)closeArray {
    if (!_closeArray) {
        _closeArray = closeArray;
        [self setupData];
    }
    _closeArray = closeArray;
}

- (UILabel *)currentMonthLabel {
    
    if (!_currentMonthLabel) {
        
        _currentMonthLabel = [[UILabel alloc] init];
        _currentMonthLabel.textAlignment = NSTextAlignmentCenter;
        _currentMonthLabel.font = [UIFont systemFontOfSize:14];
        _currentMonthLabel.textColor = [UIColor lightGrayColor];
    }
    
    return _currentMonthLabel;
}

- (UICollectionView *)collectionView {
    
    if (!_collectionView) {
        NSInteger width = self.frame.size.width / 7;
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        flowLayout.itemSize = CGSizeMake(self.frame.size.width, width * 6 + 30);
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,30,self.frame.size.width, width * 6 + 30) collectionViewLayout:flowLayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.pagingEnabled = YES;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[MonthCollectionCell class] forCellWithReuseIdentifier:@"MonthCollectionCell"];
        
    }
    return _collectionView;
}

- (NSMutableArray *)monthsArray {
    if (!_monthsArray) {
        
       _monthsArray =  [[NSMutableArray alloc] init];
    }
    
    return _monthsArray;
}

- (NSMutableArray<NSMutableArray *> *)allMonths {
    if (!_allMonths) {
        _allMonths = [[NSMutableArray alloc] init];
    }
    
    return _allMonths;
}

- (void)setup {
    
    [self addSubview:self.preBtn];
    [self addSubview:self.nextBtn];
    [self addSubview:self.currentMonthLabel];
    
    self.preBtn.frame = CGRectMake(0, 0, 80, 30);
    self.nextBtn.frame = CGRectMake(self.frame.size.width - 80, 0, 80, 30);
    self.currentMonthLabel.frame = CGRectMake((self.frame.size.width - 100)/2, 0, 100, 30);
    
    [self addSubview:self.collectionView];
  
    
}

- (NSInteger)dayslimit {
    if (_dayslimit > 0) {
        
        return _dayslimit;
    }
    
    return 120;
}

- (void)setupData {
     NSTimeInterval  oneDay = 24*60*60*1;  //1天的长度
    self.today = [NSDate dateWithTimeIntervalSinceNow:0];
    self.today = [self getSC_Date:self.today];
    
    self.preBtn.hidden = YES;
    
    self.currentMonthLabel.text = self.today.yyyyMMByLineWithDate;
    self.lastDay = [NSDate dateWithTimeIntervalSinceNow: self.dayslimit * oneDay];
    self.lastDay = [self getSC_Date:self.lastDay];
    NSDate * date = self.today;
    
    do {
        [self.monthsArray addObject:[self getCompWithDate:date]];
        [self.allMonths addObject:[self getDataDayModel:date]];
        date = [self getNextMonth:date];
        
    } while ([date compare:self.lastDay] == NSOrderedAscending ||[date compare:self.lastDay] == NSOrderedSame);
    [self.collectionView reloadData];
    
    [self showMonthWithSelecteDate:self.seletedDate];
}



- (NSMutableArray *)getDataDayModel:(NSDate *)date{
    
    NSMutableArray * daysArray = [[NSMutableArray alloc] initWithCapacity:42];;
    
    NSUInteger days = [self numberOfDaysInMonth:date];
    NSInteger week = [self startDayOfWeek:date];
    
    int day = 1;
    for (int i= 1; i<days+week; i++) {
        if (i<week) {
            [daysArray addObject:@""];
        }else{
            MonthModel *mon = [MonthModel new];
            mon.dayValue = day;
            NSDate *dayDate = [self dateOfDay:day with:date];
            mon.dateValue = dayDate;
            
            if ([dayDate compare:self.today] == NSOrderedSame && self.today ) {
                mon.isToday = YES;
            }
        
            
            if (([dayDate compare:self.today] == NSOrderedDescending  && [dayDate compare:self.lastDay] == NSOrderedAscending ) || [dayDate compare:self.today] == NSOrderedSame) {
                mon.isCanSelect = [self DateIsCanSelectWithDate:dayDate];
                if (!self.seletedDate && mon.isCanSelect) {
                    self.seletedDate = dayDate;
                }
            }
            [daysArray addObject:mon];
            day++;
        }
    }
    
    return daysArray;
}


- (BOOL)DateIsCanSelectWithDate:(NSDate *)date {
    

    for (NSString * dateStr in self.closeArray) {
        
        if ([dateStr isEqualToString:[self getYYMMDDStrWithDate:date]]) {
            
            return NO;
        }
    }
    
    return YES;
}

- (void)showMonthWithSelecteDate:(NSDate *)date{
    
    for (NSInteger i= 0; i < self.monthsArray.count; i++) {
        
        NSDateComponents * comps = self.monthsArray[i];
        if ([self getCompWithDate:date].month == comps.month) {
            
            self.currenIndex = i;
            break;
        }
    }
    
    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:self.currenIndex inSection:0];
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
}

- (void)preBtnClicked:(UIButton *)sender {
    self.currenIndex -= 1;
    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:self.currenIndex inSection:0];
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
   
}

- (void)nextBtnClicked:(UIButton *)sender {
    
    self.currenIndex += 1;
    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:self.currenIndex inSection:0];
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    self.currenIndex = scrollView.contentOffset.x / self.frame.size.width;
    NSDate *date = [self getSC_DateWithComps:self.monthsArray[self.currenIndex]];
    if (self.currenIndex == 0) {
        self.preBtn.hidden = YES;
    }else if(self.currenIndex == self.monthsArray.count - 1){
        self.nextBtn.hidden = YES;
    }else{
        self.preBtn.hidden = NO;
        self.nextBtn.hidden = NO;
    }
    self.currentMonthLabel.text = date.yyyyMMByLineWithDate;
}

#pragma mark -- MonthCollectionCellDelegate

- (void)selectDate:(NSDate *)date {
    self.seletedDate = date;
    if (_delegate && [_delegate respondsToSelector:@selector(selectTheDate:)]) {
        
        [_delegate selectTheDate:self.seletedDate];
    }
    [self.collectionView reloadData];
}
#pragma mark  --- UICollectionViewDelegate,UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.monthsArray.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MonthCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MonthCollectionCell" forIndexPath:indexPath];
   cell.delegate = self;
//    NSDateComponents * comps = self.monthsArray[indexPath.row];
    
//    NSDate * date = [self getSC_DateWithComps:comps];
    
//    [cell configData:date StartDate:self.today EndDate:self.lastDay SelectDate:self.seletedDate];
    [cell configdata:self.allMonths[indexPath.row] SelectDate:self.seletedDate];
    
    return cell;
}




#pragma mark -Private

- (NSString *)getYYMMDDStrWithDate:(NSDate *)date {
    
    
    NSDateFormatter *pickerFormatter = [[NSDateFormatter alloc] init];// 创建一个日期格式器
    [pickerFormatter setDateFormat:@"yyyyMMdd"];
    return [pickerFormatter stringFromDate:date];
}


- (NSDate *)dateOfDay:(NSInteger)day with:(NSDate *)tempDate{
    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    [greCalendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    NSDateComponents *comps = [greCalendar
                               components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay
                               fromDate:tempDate];
    comps.day = day;
    return [greCalendar dateFromComponents:comps];
}


- (NSUInteger)startDayOfWeek:(NSDate *)date
{
    NSCalendar *greCalendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    [greCalendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];//Asia/Shanghai
    NSDateComponents *comps = [greCalendar
                               components:NSCalendarUnitYear | NSCalendarUnitMonth |NSCalendarUnitWeekday | NSCalendarUnitDay
                               fromDate:[self firstDateOfMonth:date]];
    return comps.weekday;
}


- (NSDate *)firstDateOfMonth:(NSDate *)date{
    NSCalendar *greCalendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    [greCalendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    NSDateComponents *comps = [greCalendar
                               components:NSCalendarUnitYear | NSCalendarUnitMonth |NSCalendarUnitWeekday | NSCalendarUnitDay
                               fromDate:date];
    comps.day = 1;
    return [greCalendar dateFromComponents:comps];
}


- (NSUInteger)numberOfDaysInMonth:(NSDate *)date{
    NSCalendar *greCalendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    [greCalendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    return [greCalendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date].length;
    
}



- (NSDate *)getSC_Date:(NSDate *)date {
    
    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    [greCalendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    NSDateComponents *comps = [greCalendar
                               components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay
                               fromDate:date];
    
    return [greCalendar dateFromComponents:comps];
}

- (NSDate *)getSC_DateWithComps:(NSDateComponents *)comps {
    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    [greCalendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
  
    return [greCalendar dateFromComponents:comps];
}


-(NSDateComponents *)getCompWithDate:(NSDate *)date {
    
    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    [greCalendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    NSDateComponents *comps = [greCalendar
                               components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay
                               fromDate:date];
    return comps;
}


- (NSDate *)getNextMonth:(NSDate *)date{
    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    [greCalendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    NSDateComponents *comps = [greCalendar
                               components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay
                               fromDate:date];
    comps.month += 1;
    comps.day = 1;
    return [greCalendar dateFromComponents:comps];
}




@end





/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/


